import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../../common/http/global.dart';
import '../home/View/homeView.dart';
import '../home/ViewModel/homeViewModel.dart';
import '../login/Login.dart';
import '../../common/extentsion/localStorageExample.dart';
import 'package:flutter_carousel_widget/flutter_carousel_widget.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

Dio dio = Dio();

class HomePage extends StatefulWidget {
  static const String routeName = "homePage";

  HomePage({Key? key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late Future<List> _loadDataFuture; // 定义一个变量来保存Future实例
  late bool _isUserLoggedIn = false; // 假设初始为未登录状态，实际中需根据真实逻辑获取
  late CarouselController _carouselController = CarouselController(); //轮播图

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _isUserLoggedIn = (await LocalStorageExample.getBoolean('login'))!;
      if (!_isUserLoggedIn) {
        pushLogin();
      }
    });
    _loadDataFuture = loadMoreData();
  }

  pushLogin() {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) => const Login(),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          var tween = Tween(begin: const Offset(0.0, 1.0), end: Offset.zero)
              .chain(CurveTween(curve: Curves.ease));
          var offsetAnimation = animation.drive(tween);
          return SlideTransition(
            position: offsetAnimation,
            child: child,
          );
        },
        transitionDuration: const Duration(seconds: 1),
      ),
    );
  }

  //get首页数据
  Future<List> loadMoreData() async {
    var response = Api().getHome();
    return response;
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white, // 设置背景颜色为灰色
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            pinned: true,
            floating: false,
            expandedHeight: 250,
            backgroundColor: Colors.orange,
            title: buildText(),
            flexibleSpace: FlexibleSpaceBar(
              background: FutureBuilder(
                future: _loadDataFuture,
                builder: (BuildContext context,
                    AsyncSnapshot<List<dynamic>> snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    EasyLoading.show(status: '加载中...');
                    return Container();
                  } else if (snapshot.hasError) {
                    EasyLoading.showToast('图片加载失败');
                    return Container();
                  } else if (snapshot.data!.isEmpty) {
                    EasyLoading.showToast('暂无图片');
                    return Container();
                  }
                  return buildImage(snapshot.data!); // 传递处理好的图片列表数据
                },
              ),
            ),
          ),
          SliverPersistentHeader(
            pinned: true,
            delegate: MySliverPersistentHeaderDelegate(),
          ),
          SliverPadding(
            padding: const EdgeInsets.only(right: 5, left: 5, bottom: 5),
            sliver: FutureBuilder(
              future: _loadDataFuture,
              builder: (BuildContext context,
                  AsyncSnapshot<List<dynamic>> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  EasyLoading.show(status: '加载中...');
                  return const SliverToBoxAdapter();
                } else if (snapshot.hasError) {
                  EasyLoading.showToast('数据加载出现错误，请稍后再试');
                  return const SliverToBoxAdapter();
                }
                return CreatListView(data: snapshot.data!); // 传递处理好的图片列表数据
              },
            ),
          )
        ],
      ),
    );
  }

  Widget buildImage(List imageUrls) {
    final imageArr = [];
    imageUrls.asMap().entries.forEach((e) {
      if (e.key < 4) {
        if (e.value is Map && e.value.containsKey('coverImage')) {
          imageArr.add("$baseImageUrl${e.value['coverImage']}");
        }
      }
    });
    return FlutterCarousel(
      options: FlutterCarouselOptions(
        viewportFraction: 1.0,
        showIndicator: true,
        enableInfiniteScroll:true,
        autoPlay: true,
        slideIndicator: CircularSlideIndicator(
          slideIndicatorOptions: const SlideIndicatorOptions(
            indicatorRadius: 5,
          )
        ),
      ),
      items: imageArr.map((e) => buildFadeInImage(e)).toList(),
    );
  }

  Widget buildFadeInImage(String imageUrl) {
    return FadeInImage(
      width: MediaQuery.of(context).size.width,
      placeholder: AssetImage('assets/images/testphoto.jpg'),
      image: NetworkImage(imageUrl),
      fit: BoxFit.cover, // 这里设置图片的平铺方式
    );
  }

  Widget buildText() {
    return GestureDetector(
      onTap: () {
        pushLogin();
        print("容器被点击了");
      },
      child: Container(
        padding: const EdgeInsets.fromLTRB(20, 8, 20, 8),
        margin: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
        width: MediaQuery.of(context).size.width - 60,
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
          color: Colors.white.withAlpha(700),
          borderRadius: BorderRadius.circular(30),
        ),
        child: const Row(
          children: <Widget>[
            Icon(Icons.search, color: Colors.grey),
            SizedBox(width: 10),
            Text(style: TextStyle(color: Colors.grey, fontSize: 13), "点击搜索按钮"),
          ],
        ),
      ),
    );
  }
}

class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      alignment: Alignment.topLeft,
      // padding: const EdgeInsets.all(10),
      padding: const EdgeInsets.only(right: 10, left: 10, top: 10),
      color: Colors.white,
      child: const Text("为您推荐",
          style: TextStyle(
              color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold)),
    );
  }

  @override
  double get maxExtent => 35;

  @override
  double get minExtent => 35;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
